<script setup lang="ts">
import { ref, computed } from 'vue'
import { showToast, CountDown } from 'vant';

import { useUserStore } from '@/stores/user';
import { fetchDailyTask, uploadTaskEventToAdmin, fetchGetReward } from '@/api/task';
import { parseTime, uploadTaskEventToGA } from '@/utils';
import { dailyTaskIconMap, dailyTaskClickEventMap } from '@/mock/index'

import BiTaskCard from '@/components/bi-task-card/index.vue'
import BiPopup from '@/components/bi-popup/index.vue'

const userStore = useUserStore()

interface DailyTask {
    taskId: number,
    taskName: string,
    finishedNum: number,
    total: number
}

const dailyTask = ref<Array<DailyTask>>([])
const handleGetDailyTaskList = () => {
    fetchDailyTask({ deviceInfo: userStore.device }).then(res => {
        dailyTask.value = res.data.data
    }).catch(err => {
        throw new Error(err)
    })
}
handleGetDailyTaskList()
defineExpose({
    handleGetDailyTaskList
})

const handleGetTaskIconUrl = (taskId: number): string => {
    return dailyTaskIconMap[taskId].imgUrl
}

const mornCountdownAction = ref(false)
const mornPrayStyle = computed(() => {
    return mornCountdownAction.value && { fontSize: '4vmin' }
})
const morningPrayTime = ref(0)
const mornCountDown = () => {
    mornCountdownAction.value = true
    const countDownDate = Math.round(new Date(`${parseTime()} 23:59:59`).getTime());
    const now = Math.round(new Date().getTime())
    const distance = countDownDate - now

    morningPrayTime.value = distance
}

const nightCountDownAction = ref(false)
const nightPrayStyle = computed(() => {
    return nightCountDownAction.value && { fontSize: '4vmin' }
})
const nightPrayTime = ref(0)
const nightCountDown = () => {
    nightCountDownAction.value = true
    const countDownDate = Math.round(new Date(`${parseTime()} 20:00:00`).getTime());
    const now = Math.round(new Date().getTime())
    const distance = countDownDate - now

    nightPrayTime.value = distance
}
nightCountDown()

interface DailyTask {
    taskId: number,
    finishedNum: number,
    total: number,
    isReceive?: number,
    isComplete?: number
}

const showDailyRewardPopup = ref(false)
const openPopup = () => {
    showDailyRewardPopup.value = true
}
const closePopup = () => {
    showDailyRewardPopup.value = false
}
const unClaimAwardOfTask = ref<DailyTask>({} as DailyTask)
const operationDailyFn = (task: DailyTask) => {
    unClaimAwardOfTask.value = task
    const isPray = task.taskId == 1 || task.taskId == 2
    if (task.isComplete == 1 && isPray) {
        return
    }

    if (task.isComplete == 2) {
        try {
            uploadTaskEventToGA(dailyTaskClickEventMap[task.taskId].name)
            uploadTaskEventToAdmin({
                device: userStore.device,
                moduleType: 3,
                eventType: dailyTaskClickEventMap[task.taskId].id
            })
            dailyTaskIconMap[task.taskId].fn()
        } catch (error: any) {
            throw new Error(error)
        }
        return
    }

    if (task.isComplete == 1 && task.isReceive == 2) {
        openPopup()
    }
}
const handleGetFlamePoints = () => {
    uploadTaskEventToGA(dailyTaskClickEventMap[unClaimAwardOfTask.value.taskId].name)
    uploadTaskEventToAdmin({
        device: userStore.device,
        moduleType: 3,
        eventType: dailyTaskClickEventMap[unClaimAwardOfTask.value.taskId].id
    })
    fetchGetReward({
        deviceInfo: userStore.device,
        taskId: unClaimAwardOfTask.value.taskId,
        remarks: `${userStore.info.nickName} has received the award`,
        pointsType: 33, // 每日任务
        points: 20
    }).then(res => {
        if (res.data.code === 0) {
            handleGetDailyTaskList()
            closePopup()
            showToast('Receive successfully');
        }
    }).catch(err => {
        throw new Error(err)
    })
}

enum DailyTaskStatus {
    unComplete = 0,
    unReceived = 1,
    disable = 2
}
const handleGetBgColorOfDaily = (task: any): number => {
    const isPray = task.taskId == 1 || task.taskId == 2
    const paryDone = task.isComplete == 1 && isPray
    const finishTask = task.isComplete == 1 && task.isReceive == 1
    if (paryDone || finishTask) {
        return DailyTaskStatus.disable
    }

    const unReceived = task.isComplete == 1 && task.isReceive == 2
    if (unReceived) {
        return DailyTaskStatus.unReceived
    }

    return DailyTaskStatus.unComplete
}

const displayPrayTaskBtnText = (task: any) => {
    const unComplete = task.isComplete == 2 && task.isReceive == 2

    return unComplete ? 'Go' : 'Done'
}

const getDailyTaskStatusText = (task: any) => {
    const unComplete = task.isComplete == 2 && task.isReceive == 2
    if (unComplete) {
        return 'Go'
    }

    const unReceived = task.isComplete == 1 && task.isReceive == 2
    if (unReceived) {
        return 'Claim'
    }

    const isCompleted = task.isComplete == 1 && task.isReceive == 1
    if (isCompleted) {
        return "Done"
    }
}

</script>

<template>
    <div class="box">
        <div class="box-title">
            Daily Task
        </div>
        <div class="box-main">
            <ul class="list">
                <li v-for="task in dailyTask" :key="task.taskId">
                    <BiTaskCard :name="task.taskName" :icon="handleGetTaskIconUrl(task.taskId)"
                        :finish-count="task.finishedNum" :total-count="task.total" type="flame"
                        :status="handleGetBgColorOfDaily(task)" :hide-count="task.total <= 1" :hide-num="true">
                        <template #btn-slot>
                            <!-- 早祷告 -->
                            <template v-if="task.taskId == 1">
                                <div class="slot-btn" @click="!mornCountdownAction && operationDailyFn(task)"
                                    :style="mornPrayStyle">
                                    <template v-if="mornCountdownAction">
                                        <CountDown :time="morningPrayTime" @finish="nightCountDown"
                                            style="color: #fff;" />
                                    </template>
                                    <template v-else>
                                        {{ displayPrayTaskBtnText(task) }}
                                    </template>
                                </div>
                            </template>
                            <!-- 晚祷告 -->
                            <template v-else-if="task.taskId == 2">
                                <div class="slot-btn" @click="!nightCountDownAction && operationDailyFn(task)"
                                    :style="nightPrayStyle">
                                    <template v-if="nightCountDownAction">
                                        <CountDown :time="nightPrayTime" @finish="mornCountDown" style="color: #fff;" />
                                    </template>
                                    <template v-else>
                                        {{ displayPrayTaskBtnText(task) }}
                                    </template>
                                </div>
                            </template>
                            <!-- 常规任务按钮 -->
                            <div class="slot-btn" v-else @click="operationDailyFn(task)">
                                {{ getDailyTaskStatusText(task) }}
                            </div>
                        </template>
                    </BiTaskCard>
                </li>
            </ul>
        </div>
    </div>

    <!-- 每日任务获取火焰弹窗 -->
    <BiPopup :show="showDailyRewardPopup" rewards-type="flame" :rewards-num="20" button-text="Get Flame"
        @click="handleGetFlamePoints">
    </BiPopup>

</template>

<style scoped lang="scss">
.box-title {
    span {
        font-size: var(--mini-font-size);
    }
}

.list {
    background-color: #fff;
    padding: 6vmin 3vmin;

    li {
        margin-bottom: 3vmin;

        &:last-child {
            margin-bottom: 0
        }

        .slot-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
        }
    }
}
</style>